package cn.lianxw.oss.demo.controller;

import com.aliyun.oss.common.auth.ServiceSignature;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Controller
public class UploadFormController {

    private static final String ossAccessKeyId = "LTAI4GHjbA1asPofpapvxX3W";
    private static final String ossAccessSecret = "09JgoxycClhPbKTuFQoA3CrazXk6SN";

    @GetMapping("/upload/form")
    public ModelAndView form() {

        DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;

        String now = formatter.format(LocalDateTime.now().atZone(ZoneId.systemDefault()).plusSeconds(3600));

        String policy="{\"expiration\":\"" + now + "\",\"conditions\":[[\"content-length-range\", 0, 104857600]]}";
        String encodePolicy = new String(Base64.encodeBase64(policy.getBytes()));
        String signature = ServiceSignature.create().computeSignature(ossAccessSecret, encodePolicy);

        ModelAndView mv = new ModelAndView("upload");
        mv.addObject("accessKeyId",ossAccessKeyId);
        mv.addObject("policy", encodePolicy);
        mv.addObject("signature",signature);
        mv.addObject("ossKey","static/"+ UUID.randomUUID().toString()+".jpg");
        return mv;
    }

    @GetMapping("/upload/prepare")
    @ResponseBody
    public Map<String,Object> prepare() {

        DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;

        String now = formatter.format(LocalDateTime.now().atZone(ZoneId.systemDefault()).plusSeconds(3600));

        String policy="{\"expiration\":\"" + now + "\",\"conditions\":[[\"content-length-range\", 0, 104857600]]}";
        String encodePolicy = new String(Base64.encodeBase64(policy.getBytes()));
        String signature = ServiceSignature.create().computeSignature(ossAccessSecret, encodePolicy);

        Map<String,Object> response = new HashMap<>();

        response.put("accessKeyId",ossAccessKeyId);
        response.put("policy", encodePolicy);
        response.put("signature",signature);
        response.put("ossKey","static/"+ UUID.randomUUID().toString()+".jpg");

        return response;
    }


    @ResponseBody
    @GetMapping("/upload/success")
    public String Success() {
       return "success";
    }

}
